<template>
	<view class="content">
		<view class="message-content">
			<view class="day-box">
				<view class="day-item-box">
					<view class="day">
						日期
					</view>
					<view class="time">
						时间
					</view>
					<view class="money">
						金额
					</view>
				</view>
				<view class="day-item" v-for="(item,i) in viewData.paylist" :key="i">
					<view class="day">
						{{item.dayTime}}
					</view>
					<view class="time">
						{{slipTime(item.start_time) + '-' + slipTime(item.end_time)}}
					</view>
					<view class="money">
						{{item.feiyong + '元'}}
					</view>
				</view>
			</view>
			<view class="user_input_box">
				<view class="title-box">
					联系人信息
				</view>
				<view class="tel">
					<view class="title">联系人:</view>
					<input class="uni-input" focus placeholder="请输入" v-model="userFrom.name" />
				</view>
				<view class="pwd">
					<view class="title">电话:</view>
					<input class="uni-input" focus placeholder="请输入" v-model="userFrom.tel" />
				</view>
			</view>
			<!-- 会员卡余额显示 -->
			<view class="vip-yue" v-if="vipdata.isvip == true">
				<view class="title">
					会员卡余额
				</view>
				<view class="vip-box-yue">
					<view class="yue">
						余额:{{vipdata.money}}
					</view>
					<view class="item" @click="gotoVipCard()">
						充值会员卡
					</view>
				</view>
			</view>
			<view class="pay-checkbox">
				<view class="title">
					支付方式
				</view>
				<view class="pay-box">
					<!-- 微信支付 -->
					<view class="pay-item-box" :class="vipdata.checkPay == 1 ? 'active':''" @click="checkBtn(1)">
						<image class="imgs" src="../../../static/wechatpaylogo.png"></image>
						<view class="text">
							微信支付
						</view>
					</view>
					<!-- vip支付 -->
					<view class="pay-item-box" :class="vipdata.checkPay == 2 ? 'active':''" @click="checkBtn(2)">
						<image class="imgs" src="../../../static/vippaylogo.png"></image>
						<view class="text">
							{{vipdata.isvip == true ? "会员卡支付":"开通会员卡"}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bottom">
			<view class="center">
				<view class="left-money">
					<view class="p">
						合计：
					</view>
					<view class="message">
						{{'¥' + viewData.paymoney}}
					</view>
				</view>
				<view class="right-paybtn" @click="yuyue()">
					立即支付
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive
	} from 'vue';
	import {
		getVipyuePay,
		getPay,
		getOpenId,
		returnPayMessage,
		returnPayMessageFail
	} from '../../../api/api.js';
	import {
		formatDateTime
	} from '../../../tools/tools.js';

	const userFrom = reactive({
		name: '',
		tel: ''
	})

	const userOpenId = ref('')

	const viewData = reactive({
		paymoney: '',
		paylist: [],
		changguanId: 0
	});
	const yuyueList = ref([]);
	const yuyueData = ref([])
	// vip 余额
	const vipdata = reactive({
		money: 0,
		checkPay: 1,
		isvip: false,
		isPay: false
	})

	// 跳转vip注册
	const gotoVipCard = () => {
		uni.navigateTo({
			url: `/views/registeredVipView/registeredVipView?changdiId=${viewData.changguanId}`
		})
	}

	// check选择
	const checkBtn = (i) => {
		vipdata.checkPay = i
		if (vipdata.checkPay == 2 && vipdata.isPay != false) {
			gotoVipCard()
		}
	}

	// 获取openid 
	const _getOpenId = () => {
		uni.login({
			provider: "weixin",
			onlyAuthorize: true, // 微信登录仅请求授权认证
			success: function(res) {
				getOpenId(res.code).then((res2) => {
					userOpenId.value = res2.open_id
				})
			}
		})

		for (var i = 0; i < viewData.paylist.length; i++) {
			yuyueData.value.push(viewData.paylist[i].id)
			console.log(viewData.paylist[i].id, yuyueData.value);
		}
	}

	// 保存信息
	const saveWebDataBase = () => {
		let data = {
			name: userFrom.name,
			tel: userFrom.tel
		}
		uni.setStorage({
			key: 'message',
			data: data,
		});
	}

	// 信息
	const getWebDataBase = () => {
		uni.getStorage({
			key: 'message',
			success: function(res) {
				if (res.errMsg != 'setStorage:ok') {
					userFrom.name = res.data.name
					userFrom.tel = res.data.tel
				}
			}
		});
	}

	// 订阅逻辑 步骤1
	const yuyue = () => {
		if (userFrom.name === '') {
			uni.showModal({
				title: '提示',
				content: '请输入你的称呼'
			});
		} else if (userFrom.tel === '') {
			uni.showModal({
				title: '提示',
				content: '请输入你的电话'
			});
		} else {
			saveWebDataBase()
			getUserCode()
		}
	};

	// 时间格式化
	const slipTime = (item) => {
		return item.replace(/:\d{2}$/, "");
	}

	// 支付逻辑
	const getUserCode = () => {
		uni.login({
			provider: "weixin",
			onlyAuthorize: true, // 微信登录仅请求授权认证
			success: function(res) {
				payFunction(res.code)
			},
			fail: function(err) {
				console.error('登录失败', err);
			}
		})
	}

	// 支付逻辑
	const payFunction = (code) => {

		let list = []

		for (var i = 0; i < viewData.paylist.length; i++) {
			list.push(viewData.paylist[i].id)
			yuyueData.value.push(viewData.paylist[i].id)
		}

		let payData = {
			yuyueList: list,
			changdi: viewData.changdiid,
			code: code,
			changguanId: Number(viewData.changguanId),
			timeutc: Math.floor(Date.now() / 1000),
			miaoshu: `测试描述`
		}

		// 微信支付
		if (vipdata.checkPay == 1) {
			getPay(payData, '微信支付').then((res) => {

				let payJson = res

				// 计算金额并生成描述
				let amountInYuan = Number(vipdata.money) / 100;
				uni.requestPayment({
					provider: 'wxpay', // 服务提供商
					appid: payJson.appid,
					timeStamp: payJson.timeStamp.toString(),
					nonceStr: payJson.nonceStr, // 随机字符串
					package: payJson.package,
					signType: 'RSA', // 签名算法
					paySign: payJson.paySign, // 签名
					success: function(kon) {
						// 支付成功后的业务逻辑
						console.log('支付数据',kon);
						let retunData = {
							yuyueList: list,
							changdi: viewData.changdiid,
							changguanId: Number(viewData.changguanId),
							timeutc: Math.floor(Date.now() / 1000),
							miaoshu: `微信支付:金额${viewData.paymoney}`,
							money: viewData.paymoney,
							dingdanhao: res.out_trade_no,
							appointment_phone: userFrom.tel,
							appointment_person: userFrom.name,
							openid: userOpenId.value,
						}

						vipdata.isPay = true
						returnPayMessage(retunData).then((res) => {
							console.log(res);

							if (res.result == '微信预约付费成功。') {
								uni.showModal({
									title: '提示',
									content: '您已经预约成功'
								})
								setTimeout(() => {
									uni.navigateBack({
										delta: 2,
									});
								}, 3000)
							}

						})
					}
				});

			}).catch((error) => {
				console.error('获取 OpenId 失败', error);
			});
		}
		// 会员卡支付
		else if (vipdata.checkPay == 2 && vipdata.isvip == true) {
			let retunData2 = {
				yuyueList: list,
				changdi: viewData.changdiid,
				code: code,
				changguanId: Number(viewData.changguanId),
				timeutc: Math.floor(Date.now() / 1000),
				miaoshu: `测试描述`,
				appointment_phone: userFrom.tel,
				appointment_person: userFrom.name
			}

			console.log(retunData2);

			getVipyuePay(retunData2, '余额支付').then((res) => {
				console.log(res);
				if (res.result == 'VIP预约付费成功。') {
					vipdata.isPay = true
					uni.showModal({
						title: '提示',
						content: '您已经预约成功'
					})
					setTimeout(() => {
						uni.navigateBack({
							delta: 2,
						});

					}, 3000)
				}
			})
		} 
		else if (vipdata.checkPay == 2 && vipdata.isvip == false) {
			uni.showModal({
				title:'提示',
				content:'请选择使用微信支付，或者开通会员卡'
			})
			vipdata.checkPay = 1
		}
	}


	onLoad((option) => {
		viewData.paylist = JSON.parse(option.paylist)
		viewData.paymoney = Number(option.paymoney).toFixed(2)
		viewData.changguanId = option.changguanId
		viewData.isvip = option.isVip
		viewData.changdiid = option.changdi
		vipdata.isvip = (option.isVip == "true" ? true : false)
		vipdata.money = Number(option.yue).toFixed(2)
		
		console.log('vip数据',vipdata);
		console.log('页面数据',viewData 	);
		_getOpenId()
		getWebDataBase()
	});

	onUnload(() => {
		if (vipdata.isPay != true) {
			returnPayMessageFail(yuyueData.value)
		} else {

		}
	})
</script>
<style lang="scss">
	.content {
		position: relative;
		min-height: 100vh;
		background: linear-gradient(to bottom, rgba(135, 213, 255, 1) 0%, rgba(211, 211, 211, 0.58) 42%, rgba(211, 211, 211, 0) 100%);


		.message-content {
			padding: 20rpx;

			.day-box {
				border: 1rpx solid gainsboro;
				background-color: #fcfcfd;
				padding: 20rpx;
				padding-bottom: 0;
				border-radius: 20rpx;

				.day-item {
					display: flex;
					justify-content: space-around;
					margin-bottom: 20rpx;
				}
			}

			.day-item-box {
				display: flex;
				justify-content: space-around;
				margin-bottom: 30rpx;

				.day {
					padding-right: 40rpx;
				}

				.time {}

				.money {
					margin-left: 40rpx;
				}
			}

			.user_input_box {
				margin-top: 20rpx;
				border: 1rpx solid gainsboro;
				background-color: #fcfcfd;
				padding: 40rpx;
				border-radius: 30rpx;

				.title-box {
					font-size: 34rpx;
					color: #5b72f2;
					font-weight: 600;
					margin-bottom: 30rpx;
				}

				.tel {
					display: flex;
					margin-bottom: 30rpx;

					.uni-input {
						margin-left: 20rpx;
					}
				}

				.pwd {
					padding-left: 30rpx;
					display: flex;

					.uni-input {
						margin-left: 20rpx;
					}
				}
			}

			.pay-checkbox {
				margin-top: 20rpx;
				border: 1rpx solid gainsboro;
				background-color: #fcfcfd;
				padding: 40rpx;
				border-radius: 20rpx;
				margin-bottom: 100px;

				.title {
					font-size: 34rpx;
					color: #5b72f2;
					font-weight: 600;
				}

				.pay-box {

					.pay-item-box {
						display: flex;
						margin-top: 30rpx;
						padding-left: 40rpx;

						.imgs {
							display: block;
							width: 60rpx;
							height: 60rpx;
							margin-right: 20rpx;
						}

						.text {
							font-size: 30rpx;
							line-height: 60rpx;
							width: 100%;
							display: flex;
							justify-content: space-between;
						}
					}

					.active {
						background-color: #efedff;
						color: black;
						border-radius: 30rpx;
					}
				}
			}

			.vip-yue {
				margin-top: 20rpx;
				border: 1rpx solid gainsboro;
				background-color: #fcfcfd;
				padding: 40rpx;
				border-radius: 20rpx;

				.title {
					font-size: 34rpx;
					color: #5b72f2;
					font-weight: 600;
				}

				.vip-box-yue {
					margin-top: 20rpx;
					display: flex;
					justify-content: space-between;
				}
			}

		}

		.bottom {
			position: fixed;
			border-top: 1rpx solid gainsboro;
			bottom: 0;
			height: 100px;
			width: 100vw;
			background-color: white;

			.center {
				display: flex;
				justify-content: space-between;
				padding: 14px;

				.left-money {
					display: flex;

					.p {
						line-height: 60rpx;
					}

					.message {
						font-size: 50rpx;
						color: red;
					}
				}

				.right-paybtn {
					padding: 18px 28px;
					border-radius: 10px;
					background-color: #5b72f2;
					color: white;
				}
			}
		}
	}
</style>